package org.hive.testserver.domain.model.schedule;

import org.hive.testserver.domain.model.Project;
import org.hive.testserver.domain.model.Slave;
import org.hive.testserver.domain.model.Test;
import org.hive.testserver.domain.model.TestRun;
import org.hive.testserver.domain.model.TestState;
import org.hive.testserver.domain.model.WorkSheet;

/**
 * Accept tests that finished failed or broken in other test runs.
 */
public class PreviouslyBrokenAllocator extends BaseAllocatorLink {

	public PreviouslyBrokenAllocator(AllocatorLink next) {
		super(next);
	}

	private static final long serialVersionUID = 1L;

	@Override
	protected ScheduleReason scheduledReason() {
		return ScheduleReason.BROKEN_IN_EARLIER_RUN;
	}

	@Override
	protected boolean shouldAccept(Test test, Slave slave, WorkSheet workSheet) {
		return test.timesExecuted() == 0 && test.currentState() == TestState.UNTESTED && brokenInEarlierRun(test);
	}

	private boolean brokenInEarlierRun(Test test) {
		Project project = test.getTestRun().getProject();
		for (TestRun testRun : project.getTestRuns()) {
			Test otherTest = testRun.lookupTestByNameOrNull(test.getName());
			if (testRun != test.getTestRun() && otherTest != null) {
				if (otherTest.isFinished() && (otherTest.currentState() == TestState.ABORTED || otherTest.currentState() == TestState.FAILED)) {
					return true;
				}
			}
		}
		return false;
	}

}
